<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="担保客户查询"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="联系人名称"
          clearable
          @change="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="客户类型"
          clearable
          @change="getAllData()"
          v-model="params.org_class"
          :options="enumCustomerType"
        ></c-select>
      </el-form-item>
      <el-form-item v-if="isCity">
        <select-address
          v-model="params.address_code"
          auto-top
          :bottom-level="2"
          placeholder="地址查询"
          clearable
          @change="getAllData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-date-cascader
          placeholder="放款时间"
          class="form-control-ml"
          v-model="queryDate"
          @select="handleDateQuery"
        ></select-date-cascader>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumReviewApprovalSelect"
          clearable
          @change="searchParams"
          placeholder="项目状态"
          v-model="selectStatus"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.iou_no"
          placeholder="借据号"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-child-bank
          clearable
          v-model="params['bank_id.eq']"
          @change="getAllData()"
          placeholder="导入银行(可输入过滤)"
        ></select-child-bank>
      </el-form-item>
      <!-- <el-form-item>
        <el-input
          v-model="params['warranty_amount.lte']"
          v-input-number="{ fixed: 2 }"
          placeholder="放款金额小于等于"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params['warranty_amount.gte']"
          v-input-number="{ fixed: 2 }"
          placeholder="放款金额大于等于"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item> -->
      <el-form-item>
        <c-select
          v-model="params['warranty_amount.lt']"
          clearable
          placeholder="放款金额小于5万或10万"
          :options="{
            5: '放款金额小于5万',
            10: '放款金额小于10万',
          }"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params['main_business.eq']"
          placeholder="十二大产业"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.parent_main_business"
          placeholder="所属行业"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="params.batch_no"
          placeholder="批次号"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.ex_des"
          placeholder="项目异常说明"
          clearable
          @keyup.enter.native="getAllData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          v-model="params['renewal_type.eq']"
          clearable
          placeholder="展期续贷"
          :options="{
            1: '展期',
            2: '续贷',
          }"
          @change="getAllData()"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getAllData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="exportAllPages">
          导出
        </el-button>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" icon="el-icon-plus" @click="handleToEdit">新增</el-button>
        <el-button type="primary" icon="el-icon-upload2" @click="showImport">导入</el-button>
      </el-form-item> -->
      <el-form-item>
        <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">
          批量删除
        </el-button>
      </el-form-item>
      <!-- <el-form-item>
        <div class="text-danger">
          存量业务入口已关闭，暂时停止项目导入及新增。是否能以增量业务上报，请与农担业务联系
        </div>
      </el-form-item> -->
    </el-form>

    <div class="card my-2">
      <div class="card-body" v-loading="countLoading">
        <span class="h5 text-muted">
          项目共计：
          <span class="text-danger">{{ tableCount }}</span>
        </span>
        <span class="h5 text-muted ml-5">
          金额合计：
          <span class="text-danger">{{ tableFunds || '-' }}</span>
          万元
        </span>
      </div>
    </div>
    <c-table
      border
      v-loading="loading"
      ref="table"
      class="table-sm"
      :columns="tableColumns"
      row-key="customer_related_id"
      @selection-change="handleSelectionChange"
      :data="tableData"
    >
      <template v-slot:status="scope">
        <div :class="`text-${scope.row.statusStyle}`">
          <div :title="scope.row.ex_des">
            <span v-if="+scope.row.import_status > 1 && scope.row.ex_des">
              {{ scope.row.statusLabel + `: ${scope.row.ex_des}` }}
            </span>
            <span v-else>{{ scope.row.statusLabel }}</span>
          </div>
          <small :class="`text-${scope.row.replaceStatusStyle}`">
            {{ scope.row.replaceStatus }}
          </small>
          <div
            v-if="scope.row.back_reason && ![1, 2, 4, 5, 6, 7].includes(+scope.row.review_approval)"
            :class="+scope.row.import_status === 2 ? 'text-warning' : 'text-danger'"
          >
            <span v-if="+scope.row.import_status === 3">
              拒绝:
              <span v-html="xss(scope.row.back_reason)"></span>
            </span>
            <span v-else>
              退回:
              <span v-html="xss(scope.row.back_reason)"></span>
            </span>
          </div>
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="getData"
        :current-page.sync="params.index"
        :page-sizes="[15, 100, 200, 500, 1000]"
        :page-size="params.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableCount"
      ></el-pagination>
    </div>

    <project-new-dialog
      :visible.sync="applyVisible"
      :submit="toSubmit"
      :table-id="tableId"
      :form-data="applyRow"
      @success="handleSuccess()"
    ></project-new-dialog>

    <import-excel
      :excel-template="importFileUrl"
      title="导入项目信息"
      :tip="false"
      :post-api="postUrl"
      :visible.sync="importVisible"
      @success="handleImportSuccess"
    ></import-excel>

    <project-view-dialog
      :visible.sync="visible"
      :batch-no="attachNo"
      :query-id="queryId"
    ></project-view-dialog>

    <import-tip
      :visible.sync="tipVisible"
      @success="handleSuccess"
      :batch-no="batchNo"
    ></import-tip>
  </div>
</template>
<script>
import { queryTrouble } from '@vimi/utils-api'
import {
  baseTableColumns,
  dataAdapter,
  enumCustomerType,
  enumReviewApproval,
  enumReviewStyle,
  parseCascaderDate,
  enumReplaceStatus,
  enumReplaceStatusStyle,
  enumReviewApprovalSelect,
} from '@/bank/views/limit/index'

import ProjectViewDialog from '@/bank/views/business/industry/history/ProjectViewDialog'
import hndTableMixin from '@/bank/views/business/limit/history/mixins'
import SelectAddress from '@/components/select/SelectAddress'
import ProjectNewDialog from '@/bank/views/business/industry/ProjectNewDialog'
import ImportExcel from '@/components/ImportExcel'
import ImportTip from '@/bank/views/business/industry/history/import/ImportTip'
import SelectDateCascader from '@/components/select/SelectDateCascader'
import SelectChildBank from '@/bank/components/select/SelectChildBank'
import xss from 'xss'
export default {
  components: {
    ProjectViewDialog,
    SelectAddress,
    ProjectNewDialog,
    ImportExcel,
    ImportTip,
    SelectDateCascader,
    SelectChildBank,
  },
  mixins: [hndTableMixin],
  props: {},
  data() {
    return {
      xss,
      enumCustomerType,
      enumReviewApprovalSelect: {
        ...enumReviewApprovalSelect,
        100: '异常项目',
      },
      params: {
        index: 1,
        size: 15,
        customer_name: '',
        'channel_type.eq': 0,
        'import_status.eq': '',
        'is_rural_dev.eq': 1,
        subKey: 'project_apply_batch.project_apply_batch_id',
      },
      queryDate: [],
      order: {
        N1import_status: 'asc',
        N2create_time: 'desc',
        N3customer_name: 'desc',
      },
      tableName: 'datum_one_county_industry',
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            reserveSelection: true,
            selectable: this.onSelect,
          },
        },
        ...baseTableColumns,
        {
          attrs: { label: '提交银行', prop: 'submitOrg', align: 'left', width: '110px' },
        },
        {
          attrs: { label: '提交时间', prop: 'submitTime', align: 'left', width: '90px' },
        },
        {
          attrs: { label: '业务类型', prop: 'projectType', align: 'center' },
        },
        {
          attrs: { label: '产品名称', prop: 'project_type_name', align: 'center' },
        },
        {
          attrs: { label: '批次号', prop: 'batch_no', align: 'center', width: '110px' },
        },
        {
          attrs: { label: '项目状态', prop: 'statusLabel', align: 'center', width: '110px' },
          slot: 'status',
        },
        {
          attrs: { label: '操作', align: 'center', width: '160px' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleToEdit,
              ifRender: row =>
                [0, 9].includes(+row.review_approval) &&
                +row.import_status !== 3 &&
                row.bank_user_id === this.userId,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
              ifRender: row => this.onSelect(row),
            },
            { content: '查看', icon: 'fa fa-search', event: this.showCreditFile },
          ],
        },
      ],

      queryId: '',
      attachNo: '',
      visible: false,

      // 编辑
      applyVisible: false,
      applyRow: {},
      tableId: '',

      importVisible: false,

      tipVisible: false,
      batchNo: '',

      productName: '',

      selectProductVisible: false,
      selectProductId: '',
      selectStatus: '',
      toSubmit: true,
      multipleSelection: [],
      tableFunds: 0,
      countLoading: false,
    }
  },
  computed: {
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    isCity() {
      return +this.user.orgRegionLever < 3
    },
    bankName() {
      return this.org.orgName || '-'
    },
    bankCode() {
      return this.org.orgCode
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    productId() {
      return this.$route.query.id
    },
    postUrl() {
      return (
        '/api/credit/import/' +
        queryTrouble(this.tableName, {
          importKey: 'datum_one_county_industry_template_bank_ep_rural',
          'bank_name.eq': this.bankName,
          'bank_id.eq': this.clientId,
          'bank_code.eq': this.bankCode,
          'bank_type.eq': this.bankType,
        })
      )
    },
    importFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/乡村振兴贷导入模板.xlsx?${+new Date()}`
    },
    isSYSTEM() {
      // 系统后台查所有
      return this.org.orgClass === 'org_credit_sys'
    },
    pages() {
      return Math.ceil(this.tableCount / 10000)
    },
  },
  watch: {},
  created() {
    if (this.productId) {
      this.params['project_type_id.eq'] = this.productId
    }
    if (this.isSYSTEM) {
      this.params['orWhereAnd.address_code.gt'] = ''
      this.params['orWhereAnd.address_code.lt'] = ''
      this.params['orWhereAnd.bank_type.eq'] = ''
      this.params['orWhereAnd.bank_id.eq'] = ''
      this.params['orWhereAnd.bank_type.in'] = ''
      this.params.orWhereAndTemplate = ''
    }
    this.getAllData()
    this.getProduct()
  },
  mounted() {},
  methods: {
    exportAllPages() {
      const { index, size, subKey, ...params } = this.getParams()
      const requestAll = []
      for (let i = 1; i <= this.pages; i++) {
        requestAll.push(this.fetchDataTimeout({ ...params, index: i, size: 10000 }))
      }
      this.exportLoading = true
      Promise.all(requestAll)
        .then(arrRes => {
          let datas = []
          arrRes.forEach(res => {
            datas = datas.concat(res)
          })
          this.exportExcel('乡村振兴贷-存量业务', datas)
          if (this.pages > 2) {
            this.$message.warning('正在导出请耐心等待')
          }
        })
        .finally(() => {
          this.exportLoading = false
        })
    },
    getAllData(index = 1) {
      this.getData(index)
      this.getCountFunds()
    },
    getCountFunds() {
      const { index, size, ...params } = { ...this.getParams() }
      params.groupFunc = 'round(sum(warranty_amount)|2)'
      this.countLoading = true
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.tableFunds = data.p || 0
        })
        .finally(() => {
          this.countLoading = false
        })
    },
    handleSizeChange(val) {
      this.params.size = val
      this.getData(1)
    },
    searchParams(v) {
      this.params['back_reason.neq'] = ''
      this.params['review_approval.in'] = ''
      if (+v === 100) {
        this.params['import_status.in'] = '2,3'
      } else if (+v === 9) {
        this.params['import_status.in'] = '2,3'
        this.params['back_reason.neq'] = `''`
      } else {
        this.params['import_status.in'] = v ? 1 : ''
        this.params['review_approval.in'] = v
      }
      this.getAllData()
    },
    onSelect(row) {
      return (
        ([0, 3, 9].includes(+row.review_approval) || +row.import_status > 1) &&
        (row.bank_user_id === this.userId || this.user.job === 'org_corp')
      )
    },
    clearSelect() {
      this.multipleSelection = []
      const $tableRef = this.$refs.table.$children[0]
      $tableRef.clearSelection()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleBatchDelete() {
      const deleteData = []
      this.multipleSelection.forEach(item => {
        if (!item.customer_related_id) {
          return
        }
        deleteData.push(item.customer_related_id)
      })
      if (!deleteData.length) {
        return this.$message.warning('请先选择需要删除的项目')
      }
      const deleteLimit = 150
      const count = Math.ceil(deleteData.length / deleteLimit)
      const promiseAll = []

      this.$utils
        .msgbox({
          message: `确定申请删除已选的${this.multipleSelection.length}个项目?`,
          beforeClose: () => {
            for (let i = 0; i < count; i++) {
              const data = deleteData.slice(i * deleteLimit, (i + 1) * deleteLimit)
              promiseAll.push(
                this.$api.deleteData(this.$serviceName, this.tableName, data.join(','))
              )
            }
            return Promise.all(promiseAll)
          },
        })
        .then(() => {
          this.clearSelect()
          this.$message.success('删除成功')
          this.handleSuccess()
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    getProduct() {
      if (!this.productId) {
        return
      }
      this.$api
        .getData(this.$serviceName, 'industrial_package', {
          'industrial_package_id.eq': this.productId,
        })
        .then(res => {
          const data = res?.data?.[0] ?? {}
          this.productName = data.load_name
        })
    },
    setProductName(name) {
      this.productName = name
    },
    handleSuccess() {
      this.getAllData()
      this.$store.dispatch('getTaskCountIndustry', { type: 0, id: this.productId })
    },
    handleImportSuccess(data) {
      this.tipVisible = true
      this.importVisible = false
      this.selectProductVisible = false
      this.batchNo = data
    },
    dataAdapter(item) {
      dataAdapter(item)
      item.statusLabel = enumReviewApproval[item.review_approval]
      item.statusStyle = enumReviewStyle[item.review_approval]
      item.replaceStatus = enumReplaceStatus[item.is_replace] || ''
      item.replaceStatusStyle = enumReplaceStatusStyle[item.is_replace]
      const submitData = item?.project_apply_batch?.[0] ?? {}
      item.submitOrg = submitData.submit_client_name || '未申报'
      item.submitTime = submitData.create_time || '未申报'
      item.projectType = '限率业务'
      if (+item.import_status !== 1) {
        item.statusLabel = '项目异常'
        item.statusStyle = 'danger'
      }
      return item
    },
    showImport() {
      this.importVisible = true
    },
    handleDateQuery(val) {
      const [start, end] = parseCascaderDate(val)
      this.params['create_time.gte'] = start
      this.params['create_time.lte'] = end
      this.getAllData()
    },

    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除客户${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.customer_related_id),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    showCreditFile(row = {}) {
      if (+row.import_status > 1 && row.bank_id !== this.clientId) {
        this.toSubmit = false
        this.applyRow = { ...row }
        this.tableId = this.applyRow['customer_related_id'] || ''
        this.applyVisible = true
      } else {
        this.queryId = row.customer_related_id
        this.attachNo = row.project_approval_batch_bank_id || ''
        this.visible = true
      }
    },
    handleToEdit(row = {}) {
      this.toSubmit = true
      this.applyRow = { ...row }
      this.tableId = this.applyRow['customer_related_id'] || ''
      this.applyVisible = true
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
